package ru.ifmo.swing.genetics.config.factory;

import org.uncommons.watchmaker.framework.factories.AbstractCandidateFactory;
import org.uncommons.watchmaker.swing.EvolutionControl;
import ru.ifmo.common.Source;
import ru.ifmo.genetics.factory.string.AlternativeStringFactory;

import javax.swing.*;
import java.util.List;

/**
 * @author avhaliullin
 */
public class StringFactoryControl implements Source<AbstractCandidateFactory<String>>, EvolutionControl {
    private final Source<List<Character>> alphabetSource;
    private final int defaultMinLen;
    private final int defaultMaxLen;
    private final JTextField minTextField;
    private final JTextField maxTextField;


    private final JComponent control;

    public StringFactoryControl(int defaultMinLen, int defaultMaxLen, Source<List<Character>> alphabetSource) {
        this.alphabetSource = alphabetSource;
        this.defaultMinLen = defaultMinLen;
        this.defaultMaxLen = defaultMaxLen;

        control = Box.createVerticalBox();
        Box box1 = Box.createHorizontalBox();

        JLabel minLabel = new JLabel("min");
        minTextField = new JTextField(String.valueOf(defaultMinLen));
        box1.add(minLabel);
        box1.add(minTextField);

        Box box2 = Box.createHorizontalBox();

        JLabel maxLabel = new JLabel("max");
        maxTextField = new JTextField(String.valueOf(defaultMaxLen));
        box2.add(maxLabel);
        box2.add(maxTextField);

        control.add(box1);
        control.add(box2);
    }

    public JComponent getControl() {
        return control;
    }

    public void reset() {
        minTextField.setText(String.valueOf(defaultMinLen));
        maxTextField.setText(String.valueOf(defaultMaxLen));
    }

    public void setDescription(String description) {
        control.setToolTipText(description);
    }

    public AbstractCandidateFactory<String> create() {
        return new AlternativeStringFactory(
                Integer.valueOf(minTextField.getText()),
                Integer.valueOf(maxTextField.getText()),
                alphabetSource.create());
    }
}
